require('dotenv').config({path: '.env'})
const PORT = process.env.PORT
const HOST = process.env.HOST
const jwtSecretKey = process.env.jwtSecretKey
const expiresIn = process.env.expiresIn

const express = require('express')
const app = express()
const cors = require('cors')
// 解析 token 的中间件
const expressJWT = require('express-jwt')
const joi = require('joi')

app.use(function (req, res, next) {
    res.cc = function (err, status = 1) {
      res.send({
        status,
        message: err instanceof Error ? err.message : err,
      })
    }
    next()
  })



app.use(cors())
app.use(express.urlencoded({ extended: true,limit: '10mb' }))
app.use(express.json({limit: '10mb'}))
app.use(expressJWT({ secret: jwtSecretKey }).unless({ path: [/^\/user\//] }))
const path = require('path')


const userController = require('./controller/userController')
app.use('/user', userController)

const userInfoController = require('./controller/userInfoController')
app.use('/userInfo', userInfoController)

const taskController = require('./controller/taskController')
app.use('/task', taskController)

const goodsController = require('./controller/goodsController')
app.use('/goods', goodsController)

const questionController = require('./controller/questionController')
app.use('/question', questionController)


//定义错误级别的中间件
app.use((err, req, res, next) => {
    // //验证失败导致的错误
    if (err instanceof joi.ValidationError) return res.cc(err);
    //身份认证失败后的错误
    if (err.name === 'UnauthorizedError') return res.status(401).cc('身份认证失败！');
    //未知的错误
    res.cc(err);
})

app.use('/static',express.static(path.join(__dirname,'public')))

app.listen(PORT, function () {
    console.log(`api server running at http://${HOST}:${PORT}`)
  })